import { PassportStrategy } from '@nestjs/passport';
import { Strategy } from 'passport-jwt';
import type { StrategyOptions } from 'passport-jwt';
import { Injectable } from '@nestjs/common';
import { UserService } from 'src/user/user.service';
import { UserEntity } from 'src/user/entities/user.entity';
import { BusinessException } from '../exceptions/business.exception';
@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
  // 这里的 Strategy 必须是 passport-jwt 包中的
  constructor(private readonly userService: UserService) {
    super({
      jwtFromRequest: (request) => {
        let token = null;
        if (request && request.headers['token']) {
          token = request.headers['token'];
        }
        return token;
      },
      secretOrKey: '加密',
    } as StrategyOptions);
  }

  async validate(payload: UserEntity) {
    const existUser = await this.userService.findOne(payload.id);
    if (!existUser) BusinessException.throwForbidden();
    return existUser;
  }
}
